<template>
	<view class="publish-main">
		<!-- <uv-alert :title="noticetext" type="warning" :show-icon="true"></uv-alert> -->
		<uv-notice-bar :text="noticetext" bgColor="#fdf6ec" color="#fe9900"></uv-notice-bar>
		<uv-form :model="FormData" label-width="100">
			<view class="uv-card">
				<uv-text text="基本信息" bold margin="5px 0 10px 0"></uv-text>
				<uv-form-item label="品牌车型" required borderBottom @click="toselectcar">
					<uv-input disabled disabledColor="#ffffff" placeholder="选择品牌" border="none"
						v-model="FormData.title"></uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item required label="销售价格" borderBottom>
					<uv-input placeholder="请填写卖给同行的价格" v-model="FormData.money" border="none"></uv-input>
					<template v-slot:right>
						<text>万元</text>
					</template>
				</uv-form-item>
				<uv-form-item label="车辆介绍">
					<uv-textarea type="textarea" placeholder="可填写上牌日期公里数" v-model="FormData.content"
						border="bottom" :customStyle="{padding: '2px'}"></uv-textarea>
				</uv-form-item>
			</view>
			<view class="uv-card">
				<view class="uv-card_header">
					<view class="uv-card_header_title">
						<uv-text bold text="车辆图片(1-9)张" margin="5px 0 10px 0"></uv-text>
					</view>
				</view>
				<view class="uv-card_body">
					<uv-upload :max-count="9" multiple :fileList="fileList" @afterRead="afterRead"
						:previewFullImage="true" name="img" :sizeType="['compressed']" @delete="deletePic"></uv-upload>
				</view>

			</view>
			<view class="uv-card">
				<uv-row>
					<uv-col :span="6">
						<view>
							<view class="uv-card_header_title margin-bottom-sm">
								出险报告
							</view>
							<view class="uv-card_body">
								<uv-upload name="chuxian" :maxCount="1" :fileList="chuxianfileList"
									@afterRead="afterRead"></uv-upload>
							</view>
						</view>
					</uv-col>
					<uv-col :span="6">
						<view>
							<view class="uv-card_header_title margin-bottom-sm">
								维保报告
							</view>
							<view class="uv-card_body">

								<uv-upload name="weibao" :maxCount="1" :fileList="weibaofileList"
									@afterRead="afterRead"></uv-upload>
							</view>
						</view>
					</uv-col>
				</uv-row>

			</view>
			<view class="uv-card">
				<view class="uv-card_header">
					<view class="uv-card_header_title">
						<uv-text text="其他选项" bold margin="5px 0 10px 0"></uv-text>
					</view>
					<view class="uv-card_header_extra">
						<!-- <uv-icon v-if="showExtra" name="arrow-up" label="收起" @click="handleMore(false)" />
						<uv-icon v-else name="arrow-down" label="展开" @click="handleMore(true)" /> -->
					</view>
				</view>

				<!--  v-if="showExtra" -->
				<view class="uv-card_body">
					<!-- 
					<uv-form-item label="车架号">
						<uv-input v-model="FormData.frameno"></uv-input>
					</uv-form-item>
					<uv-form-item label="表显里程">
						<uv-input v-model="FormData.mileage"></uv-input>
						<template v-slot:right>
							<text>万公里</text>
						</template>
					</uv-form-item>

					<uv-form-item label="初次上牌日" @click="opendate('regtime')">
						<uv-input v-model="FormData.regtime" disabled disabledColor="#ffffff" placeholder="请填写"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>

					<uv-form-item label="保险到期日" @click="opendate('insuretime')">
						<uv-input v-model="FormData.insuretime" disabled disabledColor="#ffffff" placeholder="请填写"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>

					<uv-form-item label="年审到期日" @click="opendate('reviewtime')">
						<uv-input v-model="FormData.reviewtime" disabled disabledColor="#ffffff" placeholder="请填写"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>
					
-->
					<!-- 	<uv-form-item label="车牌归属地" @click="openprov(0)" borderBottom>
						<uv-input v-model="FormData.location" disabled disabledColor="#ffffff" placeholder="请填写"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item> -->

					<uv-form-item label="车源所在地" @click="openprov(1)" borderBottom>
						<uv-input v-model="FormData.platelocation" disabled disabledColor="#ffffff" placeholder="请填写"
							border="none"></uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>
					<uv-form-item label="使用性质" borderBottom>
						<uv-input placeholder="非营运" border="none" v-model="FormData.used"></uv-input>
					</uv-form-item>
					<uv-form-item label="过户次数" borderBottom>
						<uv-input v-model="FormData.transferno" border="none"></uv-input>
						<template v-slot:right>
							<text>次</text>
						</template>
					</uv-form-item>
					<uv-form-item label="能源类型" borderBottom>
						<uv-input placeholder="汽油" v-model="FormData.energytype" border="none"></uv-input>
					</uv-form-item>
					<uv-form-item label="联系电话" borderBottom>
						<uv-input v-model="FormData.tel" placeholder="联系方式" border="none"></uv-input>
					</uv-form-item>
				</view>
			</view>
		</uv-form>
		<view class="publish-nav">
			<view class="publish-nav-box flex">
				<view class="publish-nav-box_left" v-if="!isUpdata">
					<view class="goods-nav-icon_item">
						<uv-text type="error" text="元" align="center"></uv-text>
						<uv-text type="info" text="需支付" align="center" :size="13"></uv-text>
					</view>
				</view>
				<view class="publish-nav-box_right">
					<view class="goods-nav-button_item">
						<uv-button v-if="isUpdata" :loading="Loding" type="primary" shape='circle'
							@click="updatacar">提交更改</uv-button>
						<uv-button v-else :loading="Loding" type="primary" shape='circle'
							@click="publishcar">发布</uv-button>
					</view>
				</view>
			</view>
		</view>
		<!-- 日期picker -->
		<uv-datetime-picker ref="date_regtime" mode="date" :value="datevalue"
			@confirm="dateconfirm()"></uv-datetime-picker>
		<!-- 地区picker -->
		<uv-picker ref="picker" :columns="addressList" :loading="loading" keyName="name" @change="changepicker"
			@confirm="pickerconfirm"></uv-picker>
		<!-- 提交加载 -->
		<!-- <uv-loading-page style="z-index: 9999" :loading="Loding" :loading-text="loadinText" font-size="24rpx"
			bg-color="rgba(0, 0, 0, 0.3)"></uv-loading-page> -->
		<view style="height: 100rpx"></view>
	</view>
</template>

<script>
	import { timespantoYMD, imageCompress } from '@/common/tools.js'
	import baseconfig from '@/config.js'
	import { uploadCarInfo, uploadCarImg, queryCarInfo, updateCarInfo, removeCarImg } from '@/utils/http.js'
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				Loding: false,
				loadinText: '发布中。。。',
				FormData: {
					id: 0,
					title: '',
					tel: '',
					energytype: '汽油',
					transferno: 0,
					used: '非营运',
					location: '',
					platelocation: '',
					content: '',
					money: '',
					frameno: '',
					mileage: '',
					regtime: null,
					insuretime: null,
					reviewtime: null,
				},
				imgInfoId: 0,
				fileList: [],
				chuxianfileList: [],
				weibaofileList: [],
				notSendFileList: [],
				datename: '',
				datevalue: '',
				showExtra: false,
				isUpdata: false,
				prov_picker: {
					value: [0, 0, 0],
					select: 0,
				},
				urlparm: {}, //携带的车型信息
				addressList: []
			}
		},
		created() {

		},
		onLoad(option) {
			uni.$on('car_brand', this.setbrand)
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('car_edit', this.handeledit)
			this.FormData.platelocation = `${this.userInfo.province} ${this.userInfo.city}`
			this.FormData.location = `${this.userInfo.province} ${this.userInfo.city}`
			this.FormData.tel = `${this.userInfo.phone}`

		},
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo,
				city: state => state.area.city,
				country: state => state.area.country,
				province: state => state.area.province,
				topPackage: state => state.syspackage.topPackage,
				vipCount: state => state.user.vipCount
			}),
			noticetext() {
				var text = ''
				if (this.vipCount.upload == -1) {
					text = '会员不限量发布'
				} else {
					text = `您还可免费发布${this.vipCount.upload}条，超出条数请开通会员不限量发布`
				}
				return text
			},
			// addressList() {
			// 	return [this.provinces, this.citys, this.areas]
			// },
		},
		methods: {

			deletePic(event) {
				var f = {}
				switch (event.name) {
					case 'weibao':
						break;
					default:
						f = this.fileList[event.index]
						f.name = event.name
						this.fileList.splice(event.index, 1)
						break
				}
				if (f.status == "success") {

					var parm = { infoid: this.FormData.id, imgsrc: f.serverurl, imgtype: f.name }
					removeCarImg(parm).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: "操作成功"
							})
						}
					})
				}

			},
			handleMore(show) {
				this.showExtra = show
			},
			handeledit(e) {
				this.isUpdata = true
				this.imgInfoId = e.id
				queryCarInfo({ id: e.id }).then(res => {
					const { car } = res.data
					this.FormData = car
					this.imgInfoId = e.id
					var imglist = car.imgsrc ? car.imgsrc.split(',') : []
					this.fileList = []
					imglist.forEach(arr => {
						var _t = {
							status: 'success',
							message: '已上传',
							url: baseconfig.api_url + arr,
							serverurl: arr
						}
						this.fileList.push(_t)
					})
					if (car.weibaosrc) {
						this.weibaofileList = [{
							status: 'success',
							message: '已上传',
							url: baseconfig.api_url + car.weibaosrc,
							serverurl: car.weibaosrc
						}]
					}
					if (car.chuxiansrc) {
						this.chuxianfileList = [{
							status: 'success',
							message: '已上传',
							url: baseconfig.api_url + car.chuxiansrc,
							serverurl: car.chuxiansrc
						}]
					}
					const t = `${car.brand} ${car.subbrand} ${car.year} ${car.cartype}`
					this.FormData.title = t
				})
			},
			setbrand(e) {
				this.FormData.cartypeid = e.car.id
				this.FormData.brandid = e.brand.id
				this.FormData.subbrandid = e.series.id
				const t = `${e.brand.name} ${e.series.name} ${e.car.year} ${e.car.cartype}`
				this.FormData.title = t
			},
			updatacar() {
				this.Loding = true
				updateCarInfo(this.FormData).then(res => {
					const { code } = res
					if (code === 200) {
						this.upLoadImgs()
						uni.showToast({ title: '更新成功' })
						setTimeout(() => {
							uni.switchTab({ url: '/pages/index/index' })
						}, 2 * 1000)
					} else {
						uni.showToast({ title: '发布失败', icon: 'fail' })
						this.loading = false
					}
				})
			},
			upLoadImgs() {
				if (this.fileList.length > 0) {
					for (var i = 0; i < this.fileList.length; i++) {
						if (this.fileList[i].status == "wait") {
							this.fileList[i].status == "loading"
							var uploadinfo = { infoid: this.FormData.id, imgtype: this.fileList[i].name }
							uploadCarImg(this.fileList[i], uploadinfo).then(res => {
								const { code } = res
								if (code == 200) {
									this.fileList[i].status == "success"
								}
							})
						}
					}
				}
				if (this.weibaofileList.length > 0 && this.weibaofileList[0].status == 'wait') {
					var f = this.weibaofileList[0]
					var uploadinfo = { infoid: this.FormData.id, imgtype: f.name }
					uploadCarImg(f, uploadinfo).then(res => {
						const { code } = res
						if (code == 200) {
							this.weibaofileList[0].status == "success"
						}
					})
				}
				if (this.chuxianfileList.length > 0 && this.chuxianfileList[0].status == 'wait') {
					var f = this.chuxianfileList[0]
					var uploadinfo = { infoid: this.FormData.id, imgtype: f.name }
					uploadCarImg(f, uploadinfo).then(res => {
						const { code } = res
						if (code == 200) {
							this.chuxianfileList[0].status == "success"
						}
					})
				}
			},
			publishcar() {
				this.Loding = true
				this.FormData.infoid = this.FormData.id
				this.FormData.id = 0
				this.FormData.imgcount = this.fileList.length
				this.FormData.infoid = this.imgInfoId

				uploadCarInfo(this.FormData).then(res => {
					const { code, data } = res
					if (code === 200) {
						this.FormData.id = data.infoid
						this.upLoadImgs()
						setTimeout(() => {
							uni.switchTab({ url: '/pages/index/index' })
						}, 2 * 1000)
					} else {
						uni.showToast({ title: '发布失败', icon: 'fail' })
						this.loading = false
					}
				})
			},


			changepicker(e) {
				if (this.loading) return
				const { columnIndex, index } = e
				// 改变了省 
				if (columnIndex === 0) {
					const _p = this.province[index]
					const citys = this.city[_p.id]
					this.prov_picker.value[0] = index
					if (this.addressList.length > 2) {
						const countrys = this.country[citys[0].id]
						this.addressList = [this.province, citys, countrys]
						this.$refs.picker.setIndexs([index, 0, 0])
					} else {
						this.addressList = [this.province, citys]
						this.$refs.picker.setIndexs([index, 0])
					}


				} else if (columnIndex === 1) {
					if (this.addressList.length == 2) return
					const citys = this.addressList[1]
					const _city = citys[index]
					const _countrys = this.country[_city.id]

					this.addressList = [this.province, citys, _countrys]
					this.$refs.picker.setIndexs([this.prov_picker.value[0], index, 0])
				}
			},
			toselectcar() {
				const url = '/pages/brand/brand'
				uni.navigateTo({ url: url })
			},

			afterRead(event) {
				let lists = [].concat(event.file)

				switch (event.name) {
					case 'chuxian':
						this.chuxianfileList = []
						lists.map(item => {
							this.chuxianfileList.push({
								...item,
								status: 'wait',
								message: '等待上传',
								name: "chuxian"
							})
						})
						break;

					case 'weibao':
						this.weibaofileList = []
						lists.map(item => {
							this.weibaofileList.push({
								...item,
								status: 'wait',
								message: '等待上传',
								name: "weibao"
							})
						})

						break;

					default:
						let fileListLen = this.fileList.length
						lists.map(item => {
							this.fileList.push({
								...item,
								status: 'wait',
								message: '上传中',
								name: "img"
							})

						})
						break;
				}


			},
			openprov(type) {
				// 初始化picker
				this.prov_picker.select = type

				var _area_arr = []
				if (type == 0) {
					_area_arr = this.FormData.location.split(" ")
				} else {
					if (this.FormData.platelocation) {
						_area_arr = this.FormData.platelocation.split(" ")
					} else {
						_area_arr = ["北京市", "北京市", "东城区"]
					}

				}
				var citys = []
				var countrys = []

				var pname = _area_arr[0] ? _area_arr[0] : ''
				var _p_index = this.province.findIndex((arr) => arr.name == pname)
				_p_index = _p_index == -1 ? 0 : _p_index
				citys = this.city[this.province[_p_index].id]

				var cityname = _area_arr[1] ? _area_arr[1] : ''
				var _city_index = citys.findIndex((arr) => arr.name == cityname)
				_city_index = _city_index == -1 ? 0 : _city_index
				countrys = this.country[citys[_city_index].id]

				var coutryname = _area_arr[2] ? _area_arr[2] : ''
				var _coutry_index = countrys.findIndex((arr) => arr.name == coutryname)
				_coutry_index = _coutry_index == -1 ? 0 : _coutry_index
				if (type == 1) {
					this.addressList = [this.province, citys, countrys]
					this.$refs.picker.setIndexs([_p_index, _city_index, _coutry_index])
				} else {
					this.addressList = [this.province, citys]
					this.$refs.picker.setIndexs([_p_index, _city_index])
				}
				this.$refs.picker.open()
			},
			pickerconfirm(e) {
				if (this.prov_picker.select === 0) {
					this.FormData.location = `${e.value[0].name} ${e.value[1].name}`
				} else {
					this.FormData.platelocation = `${e.value[0].name} ${e.value[1].name} ${e.value[2].name}`
				}
			},
			opendate(refname) {
				this.datename = refname
				this.$refs.date_regtime.open()
			},
			dateconfirm(e) {
				this.FormData[this.datename] = timespantoYMD(e.value)
			},
		},
	}
</script>
<style lang="scss">
	.publish-main .uv-upload__wrap__preview{
		margin: 0 6upx 8upx 0 !important;
	}
	.publish-main .uv-upload__button{
		margin: 0 6upx 8upx 0 !important;
	}
	.publish-main .uv-card {
		margin: 20upx 0;
		padding: 20upx 40upx;
	}
	.publish-main .uv-cell__left-icon-wrap{
		margin:0 !important;
	}
	.publish-main {
		margin-bottom: 50rpx;
	}

	.publish-nav {
		display: flex;
		position: fixed;
		width: 100%;
		bottom: 0px;
		padding: 15rpx;
		background-color: #fff;
		z-index: 900;

		.publish-nav-box {
			flex-direction: row;
			flex: 1;
			height: 90rpx;
			background-color: #fff;
			padding: 2rpx 15rpx;

			&_left {
				padding: 0 5px;
				width: 120rpx;

			}

			&_right {
				text-align: center;
				flex: 1;
				margin: 0 5rpx;
				flex-direction: row;
			}
		}
	}
</style>